package controllers

import (
	"github.com/astaxie/beego"
	"servermg/log"
	"servermg/models"
	"servermg/protocol"
	"servermg/socket"
	"strconv"
)

const (
	CONTROL_LOG_INFO = 0x111 //控制日志等级CMD
)

const (
	GET_LOG_LV = -1
)

type OptsController struct {
	beego.Controller
}

func (c *OptsController) Get() {
	c.TplName = "opts.html"
}

func (this *OptsController) Log() {
	log.Error("opts Log")
	this.TplName = "opts.html"
	this.Data["Stypes"] = models.GetStypeByOpt(models.OPT_LOG_INFO)
}

func (this *OptsController) Logfind() {

	this.TplName = "opts.html"
	stype := this.Input().Get("id")
	var err error
	this.Data["Stypes"] = models.GetStypeByOpt(models.OPT_LOG_INFO)
	servers, err := models.GetStypeServer(stype)
	if err != nil {
		log.Error(err.Error())
		this.Redirect("/opts", 302)
		return

	} else {
		slogs := make([]*models.ServerLog, 0)
		for _, sv := range servers {
			sl := logInfo(sv, GET_LOG_LV)
			slogs = append(slogs, sl)
		}
		this.Data["Tid"] = stype
		this.Data["Servers"] = slogs
	}
}

func (this *OptsController) Logset() {
	log.Error("opts Logset")
	id := this.Input().Get("id")
	lv := this.Input().Get("lv")
	type_id := this.Input().Get("tid")
	log.Error("svid[%s] lv[%s], stype", id, lv, type_id)

	id_num, err := strconv.ParseInt(id, 10, 64)
	lv_num, err := strconv.ParseInt(lv, 10, 64)
	server := models.GetServerById(id_num)
	if server != nil && err == nil {
		logInfo(server, int(lv_num))
		url := "/opts/logfind?id=" + type_id
		this.Redirect(url, 302)

	}
	this.Redirect("/opts", 302)
	return
}

func logInfo(server *models.Server, lv int) *models.ServerLog {

	addr := server.Addr + ":" + strconv.Itoa(server.Port)

	client := socket.Connect(addr)
	if client != nil {

		defer client.Close()
		pkg := new(protocol.BoyaaPacket)
		pkg.WriteBeginQE1(CONTROL_LOG_INFO)
		pkg.WriteInt(int32(lv))
		pkg.WriteEnd()

		client.SendPacket(pkg)

		info := client.Receiver()
		old_lv := info.ReadInt()
		cur_lv := info.ReadInt()

		log_info := &models.ServerLog{*server, int(old_lv), int(cur_lv)}
		log.Error("log info addr[%s],old_lv[%d], cur_lv[%d]", addr, old_lv, cur_lv)

		return log_info
	}
	log.Error("log connect fail addr[%s]", addr)
	return nil
}
